﻿#pragma execution_character_set("utf-8")
/*
 *  _DEBUG 是debug 版本定义的宏
 *
 */

#include "MainWindow.h"
#include "ui_MainWindow.h"
#include<QtSql/QSqlDatabase>
#include<QtSql/QSqlError>
#include<QMessageBox>
#include<QDebug>
#include<array>
#include<QtSql/QSqlQuery>
#include<QStringList>
#include<QtSql/QSqlRecord>
#include<QtSql/QSqlQueryModel>
#include<QTimer>
#include <QTime>
#include<QPicture>
#include<QMenu>
#include<QAction>
#include<QMenuBar>
#include<QStringListModel>
using std::array;

constexpr int MainWindow:: CLOSECONN;
//------------------------------------------------
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    model = new QSqlTableModel(this);
    ui->tableView->setModel(model);
    conn = QSqlDatabase::addDatabase("QMYSQL");
    setAttribute();                     //设置控件的属性
    setConnect();						//链接处理函数
    setStatusBar(mStaLabel);			//设置外部状态栏
    QTime time =QTime::currentTime();
    auto ter = new QTimer(this);
    ter->start(1000);
    connect(ter,SIGNAL(timeout()),this,SLOT(onTimerUp()));
    mStaLabel->setText("使用之前请阅读说明文档"+time.currentTime().toString());
    setFixedSize(width(), height());
    setWindowTitle("create by_自在星成");
    QString sqlType = ui->cmbsql->currentText().toLower();


    auto souac = new QAction(QIcon(":image/sousuo.png"),"执行sql",this);
    ui->lineEditSql->addAction(QIcon(":image/sql.png"),QLineEdit::LeadingPosition);
    ui->lineEditSql->addAction(souac,QLineEdit::TrailingPosition);
    connect(souac,SIGNAL(triggered(bool)),this,SLOT(onBtnExecSql()));
    auto lists =ui->lineEditSql->actions();
    qDebug()<<"list is "<<lists;
    //    QString strDBLocallHost = "127.0.0.1";       //数据库的主机名
    //    QString strDBName = "hibernate";            //数据库的名称
    //    QString strDBUser = "root";                   //链接数据库的用户名
    //    QString strDBPassword = "123456";
    //    QString strTableName = "customer";				//表名


    //    conn.setDatabaseName(strDBName);
    //    conn.setHostName(strDBLocallHost);
    //    conn.setUserName(strDBUser);
    //    conn.setPassword(strDBPassword);
    //    if (!conn.open()) {
    //        auto err = conn.lastError();
    //        QString lserr = err.databaseText();
    //        QMessageBox::warning(nullptr, "error", lserr, QMessageBox::Ok);

    //    }



    //    model->setTable(strTableName);
    //    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    //    model->select(); //选取整个表的所有行



    //不显示name属性列,如果这时添加记录，则该属性的值添加不上
    // model->removeColumn(1);






#ifdef _DEBUG
    qDebug() << this->width() << "  height " << height();

#endif // _DEBUG


    // ui->lineEditSql->setPlaceholderText("在这里编写SQL语句,按下Enter开始执行.");


    //    ui->lineEditSql->setContextMenuPolicy(Qt::DefaultContextMenu);

    //    auto mex = ui->lineEditSql->createStandardContextMenu();
    //    mex ->addAction("搜做这句sql");
    //initialMenuBar();
    // qDebug()<<"rea "<<rea;y

    if (sqlType == "mysql") {
        ui->lineEdit_port->setText("3306");
    }
    else {
        ui->lineEdit_host->setText("localhost");
        ui->lineEdit_port->setText("");
    }
    ui->lineEdit_host->setText("127.0.0.1");
    ui->lineEdit_userName->setText("root");
    ui->lineEdit_userPassword->setText("123456");
    ui->lineDBName->setText("bookstore");
   // ui->cTableName->setText("hand");
    QString st1 ="show";
    QString st2 ="insert";
    QString st3= "drop";
    QString st4="sw";
    QString st5 = "sl";
    QStringList  list =(QStringList()<<st1<<st2<<st3<<st4<<st5<<"s1"<<"s2"<<"s3"<<"s4"<<"s5");

    QStringListModel *listModel = new QStringListModel(list);
    QCompleter * comm = new QCompleter(listModel);
    comm->setMaxVisibleItems(6);
    comm->setCompletionMode(QCompleter::PopupCompletion );
    ui->lineEditSql->setCompleter(comm);
}

MainWindow::~MainWindow()
{
    if (conn.isOpen()) {
        conn.close();
#ifdef  _DEBUG
        qDebug() << "conn is close";
#endif //  _DEBUG

    }
    delete ui;
}


/**
 * @brief MainWindow::event
 * @param event
 */
bool MainWindow::event(QEvent *event)
{

    if(event ->type() == QEvent::Close){
        qDebug()<<"关闭事件";

        auto re = QMessageBox::information(this,"警告","是否关闭本次链接",QMessageBox::Ok,QMessageBox::Cancel);
        qDebug()<<"re = "<<re;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::Cancel "<<QMessageBox::Cancel;
        qDebug()<<"QMessageBox::yes "<<QMessageBox::Yes;
        qDebug()<<"QMessageBox::Reset "<<QMessageBox::Reset;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;
        qDebug()<<"QMessageBox::ok "<<QMessageBox::Ok;

        if(re == QMessageBox::Ok){
            conn.close();
            event->accept();
        } else if(re == QMessageBox::Cancel)
        {
            qDebug()<<"忽略本次关闭事件";
            //忽视本次
            event->ignore();
        }

    }
    else
    {

        return QWidget::event(event);
    }

}

void MainWindow::keyPressEvent(QKeyEvent *event)
{

    qDebug()<<" ui->lineEditSql has focus "<<ui->lineEditSql->hasFocus()<<" key "<<event->key();
    //qDebug() << event->key();
    // 如果按下方向键的向上和lineEditSql获取焦点的时候
    if (event->key() == Qt::Key_Up && ui->lineEditSql->hasFocus()) {
        if (strCmd.size() != 0) {
            // 上一条sql  这里一定要用到摸除取余数
            ui->lineEditSql->setText(strCmd[--iPreCount% strCmd.size()]);
#ifdef _DEBUG

            {
                int coux = 0;
                for (auto const sc : strCmd) {
                    qDebug() << "命令行 " << coux++ << " : " << sc;
                }
            }
#endif // _DEBUG

        }
#ifdef _DEBUG
        qDebug() << "按下方向山键 strCmd'size = " << strCmd.size() << " , iPreCount = " << iPreCount;
#endif // _DEBUG
    }
    // 如果按下方向键的向下和lineEditSql获取焦点的时候
    else if (event->key() == Qt::Key_Down && ui->lineEditSql->hasFocus()) {
        if (strCmd.size() != 0) {
            // 下一条sql 这里一定要用到摸除取余数
            ui->lineEditSql->setText(strCmd[(++iPreCount % strCmd.size())]);
        }

#ifdef _DEBUG
        qDebug() << "按下方向下键 strCmd'size = " << strCmd.size() << " , iPreCount = " << iPreCount;
#endif // _DEBUG
    } //
    else if (event->key() == Qt::Key_Return &&  ui->lineEditSql->hasFocus()) {
#ifdef _DEBUG
        qDebug() << "按下Enter键 strCmd'size = " << strCmd.size() << " , iPreCount = " << iPreCount;
#endif // _DEBUG
        onBtnExecSql();
    }
    else if (event->key() == Qt::Key_Return &&  ui->cTableName->hasFocus()) {
        onBtnShow();

#ifdef _DEBUG
        qDebug() << "安下Enter 并且调用show () ";
#endif // _DEBUG
    }
    else if (event->key() == Qt::Key_Return &&  ui->lineDBName->hasFocus()) {
        onBtnConnect();

#ifdef _DEBUG
        qDebug() << "安下Enter 并且调用Connect () ";
#endif // _DEBUG
    } else if( (!ui->lineEditSql->hasFocus()) && event->key() == Qt::Key_Tab){

        ui->lineEditSql->setFocus(Qt::TabFocusReason);
    }
    else {
        //调用父类的案件处理函数
        QWidget::keyPressEvent(event);
    }
}



void MainWindow::onBtnExecSql()
{
    QString strSql = ui->lineEditSql->text().trimmed();
    if (strSql == "") {
        QMessageBox::critical(nullptr, "出错提示", "SQL语句不能为空!", QMessageBox::Ok);
        return;
    }
#ifdef _DEBUG
    qDebug() << "想要执行的sql 语句是" << strSql;



#endif // _DEBUG

    // 如果数据库没有链接
    if (!conn.isOpen()) {
        QMessageBox::critical(nullptr, "出错信息", "请确保数据库已经链接", QMessageBox::Ok);
        return;
    }

    QSqlQuery query(strSql);
    query.exec();

    delete model;
    model = nullptr;
    qDebug() << " query is active " << query.isActive();
    QSqlQueryModel sqlqModel;
    sqlqModel.setQuery(strSql);
    auto lsErr = sqlqModel.lastError();
    auto errtext = lsErr.text();
    qDebug() << "lserror" << errtext;
    auto sqlqmodel = new QSqlQueryModel(this);
    sqlqmodel->setQuery(query);
    ui->tableView->setModel(sqlqmodel);


    auto record = query.record();
    qDebug() << "record " << record;

    if (strSql.startsWith("create") || strSql.startsWith("drop") || strSql.startsWith("insert")) {
        query.exec();
        //	conn.commit();
        //model->submit();

    }

    else {
        QString strTables;
        if (query.exec()) {
            while (query.next()) {
                strTables += query.value(0).toString();
#ifdef _DEBUG
                qDebug() << "value " << query.value(0).toString();

#endif // DEBUG

            }
            query.clear();	// 清除
#ifdef _DEBUG
            qDebug() << "sql语句执行成功";

#endif
        }
        else {
            auto lsError = conn.lastError();
            auto text = lsError.text();
            QMessageBox::critical(nullptr, "出错信息", text, QMessageBox::Cancel);
            // 退出
            return;
        }
    }

    setCountPutStr(strSql);


    //清空数据
    ui->lineEditSql->clear();

}

// -------------------数据库的类型发生改变----------------
void MainWindow::onSqlTypeChange()
{
#ifdef _DEBUG
    qDebug() << "onSqlTypeChange";
#endif // _DEBUG

    QString sqlType = ui->cmbsql->currentText().toLower();
    QString strLocalHost = QString("127.0.0.1");
    QString iPortMYSQL = QString("3306");	//mySQL默认端口
    QString  iPortSER = QString("1433");		// SQLSERVER 的默认端口
    if (sqlType == "mysql") {

        ui->lineEdit_port->setText(iPortMYSQL);
    }
    else {

        ui->lineEdit_port->setText(iPortSER);
    }

    ui->lineEdit_host->setText(strLocalHost);
    ui->lineEdit_host->setText("127.0.0.1");
    ui->lineEdit_userName->setText("root");
    ui->lineEdit_userPassword->setText("123456");
    ui->lineDBName->setText("hibernate");
    //ui->cTableName->setText("customer");
}

//--------------------链接数据库--------------------
// 先判断是否有链接的实例
void MainWindow::onBtnConnect()
{
#ifdef _DEBUG
    qDebug() << "onBtnConnect";

#endif
    // 获取数据的链接类型
    QString strSqlType = ui->cmbsql->currentText().toLower();
    QString strDbType;



#ifdef _DEBUG
    qDebug() << " db name " << ui->lineDBName->text().trimmed().toLower() << " connect " << conn.databaseName().trimmed().toLower();

    qDebug()<<__LINE__<<"conn.isOpen() "<<conn.isOpen();
#endif // _DEBUG
    // 判断数据是否存在链接实例
    if (conn.isOpen() && ui->lineDBName->text().trimmed().toLower() == conn.databaseName().trimmed().toLower())
    {
        QMessageBox::information(nullptr, "提示信息", "当前数据库正在链接", QMessageBox::Ok);
        return;


    }
    else if (conn.isOpen())
    {
        auto re = QMessageBox::warning(nullptr, "提示信息", "当前存在一一个正在链接的数据库,\n 是否断开当前的链接?", QMessageBox::Ok, QMessageBox::Cancel);
        if (re == QMessageBox::Cancel)
        {
            return;
        }
        else
        {
            //断开链接
            onBtnDisConnect();
            return;
        }
    }
    else
    {		// 数据库的链接实例为空

        if (strSqlType == "sqlserver")
        {
            strDbType = "QODBC3";
        }
        else
        {
            strDbType = "Q" + ui->cmbsql->currentText().trimmed().toUpper();	// 数据库类型
        }

        QString strDbHostName = ui->lineEdit_host->text().trimmed();				//逐句名
        int iDbPort = ui->lineEdit_port->text().trimmed().toInt();					//端口号
        QString strDbUserName = ui->lineEdit_userName->text().trimmed();			// 用户名
        QString strDbUserPassword = ui->lineEdit_userPassword->text().trimmed();	//用户密码
        QString strDbName = ui->lineDBName->text().trimmed();						//数据库名
        // strTableName = ui->cTableName->text().trimmed();			//表名
#ifdef _DEBUG
        qDebug() << "strDbType = " << strDbType;
        qDebug() << "strDbHostName = " << strDbHostName;
        qDebug() << "iDbPort = " << iDbPort;
        qDebug() << "strDbUserName = " << strDbUserName;
        qDebug() << "strDbUserPassword = " << strDbUserPassword;
        qDebug() << "strDbName = " << strDbName;
      //  qDebug() << "strTableName = " << strTableName;

#endif // _DEBUG

        qDebug() << "connection 'name " << conn.connectionName();

        // 设置链接属性
        QString name;
        {

            name = QSqlDatabase::database().connectionName();

        }
        conn.removeDatabase(name);

        conn = QSqlDatabase::addDatabase(strDbType);
        conn.setDatabaseName(strDbName);
        conn.setHostName(strDbHostName);
        conn.setPort(iDbPort);
        conn.setUserName(strDbUserName);
        conn.setPassword(strDbUserPassword);
        // 链接数据库
        if (!conn.open()) {
            auto lsError = conn.lastError();
            auto text = lsError.text();
            qDebug() << "errorMessage" << text;
            QMessageBox::critical(nullptr, "请检查以下属性", text, QMessageBox::Ok);
            return;
        }
        else {
            auto list = conn.tables();
            /***
                修改 2017年11月16日
            */
            if (list.count() > 0) {
                ui->cTableName->clear();
                ui->cTableName->addItems(list);
            }
            list.sort();


            QString tables = "存在一些表 \n";
            int iCount = 0;
            for (auto cs : list) {
                tables = tables +QString::number(iCount++) +"  :  "+ cs + "\n";
            }

            QMessageBox::information(nullptr, "提示信息", tables, QMessageBox::Ok);
#ifdef _DEBUG
            qDebug() << " dynamic_cast" << model;
            qDebug() << "model = " << model;
#endif // _DEBUG



#ifdef _DEBUG
          //  qDebug() << "table name" << strTableName;
            if (model) {
                qDebug() << " 当前的行数 " << model->rowCount();
            }
#endif // _DEBUG


        }
    }

    setWindowTitle(conn.databaseName() + "__");

    ui->btn_connect->setEnabled(false);
    ui->btn_disConnect->setEnabled(true);
    ui->btn_modify->setEnabled(true);
    ui->btn_undomodify->setEnabled(true);
    ui->btn_input->setEnabled(true);
    ui->btn_delete->setEnabled(true);
    ui->btn_show->setEnabled(true);
    ui->btn_execSql->setEnabled(true);
}
//--------------------断开数据库的链接-----------------------
void MainWindow::onBtnDisConnect()
{
#ifdef _DEBUG
    qDebug() << "onBtnDisConnect";
#endif //_DEBUG

    // 判断当前是否有数据库正在链接
    if (!conn.isOpen()) {
        auto lsError = conn.lastError();
        auto errText = lsError.databaseText() + lsError.driverText() + lsError.text() + lsError.nativeErrorCode();

#ifdef _DEBUG
        qDebug() << "databaseText" << lsError.databaseText();
        qDebug() << "text" << lsError.text();
        qDebug() << "driverText" << lsError.driverText();
        qDebug() << "nativeErrorCode" << lsError.nativeErrorCode();
        qDebug() << "databaseName" << conn.databaseName();
#endif _DEBUG

        errText = "当前无连接数据库";
        QMessageBox::warning(nullptr, "出错信息", errText, QMessageBox::Ok);
    }

    else {

        auto reValid = conn.isValid();
        if (reValid)
        {
            qDebug() << __LINE__ << "databasle'name " << conn.databaseName();
            QString strDBName;
            {
                strDBName = conn.databaseName();
            }
#ifdef _DEBUG
            qDebug() << "model " << ui->tableView->selectionModel();
            qDebug() << "db's name " << strDBName;
#endif // _DEBUG
        }
        else
        {
            qDebug() << " conn 已经无效了";
        }
        conn.close();

        qDebug()<<__LINE__<<" is open " << conn.isOpen();
        QMessageBox::information(nullptr, "tips", "数据断开链接成功", QMessageBox::Ok);
        setWindowTitle("create by_ 自在星成");
        if (model)
        {
            model->clear();
        }
    }
    ui->btn_connect->setEnabled(true);
    ui->btn_disConnect->setEnabled(false);
    ui->btn_modify->setEnabled(false);
    ui->btn_undomodify->setEnabled(false);
    ui->btn_input->setEnabled(false);
    ui->btn_delete->setEnabled(false);
    ui->btn_show->setEnabled(false);
    ui->btn_execSql->setEnabled(false);


    //重新设置状态
   ui->cTableName->clear();
    ui->cTableName->addItem("请先链接数据库");

}

void MainWindow::onBtnModify()
{
#ifdef _DEBUG
    qDebug() << "onBtnModify";
#endif //_DEBUG
    auto res = QMessageBox::warning(nullptr, "提示信息", "是否提交修改", QMessageBox::Ok, QMessageBox::Cancel);
    if (res == QMessageBox::Ok) {
        auto re = model->submitAll();
        if (re) {
            return;
        }
        else {

            auto lsError = model->lastError();
            auto text = lsError.text();
            auto re = QMessageBox::critical(nullptr, "出错信息", text + "\n 是否退出本次操作", QMessageBox::Ok, QMessageBox::Cancel);
            if (re == QMessageBox::Ok) {
                model->revertAll();
            }
            else {
                return;
            }

        }
    }
    else {

        model->revertAll();
    }
}

void MainWindow::onBtnUnModify()
{
#ifdef _DEBUG
    qDebug() << "onBtnUnModify";
#endif //_DEBUG

    model->revertAll();



}

void MainWindow::onBtnInput()
{
#ifdef _DEBUG
    qDebug() << "onBtnInput";
#endif //_DEBUG

    auto iCount = model->rowCount(); //获取行号
#ifdef _DEBUG
    qDebug() << " 行号是 " << iCount;
#endif
    model->insertRow(iCount);
    //model->setData(model->index(0, iCount + 1));
    // 	auto re = model->submitAll();
    //
    // 	if (!re) {
    // 		// 如果提交不成功
    // 		auto lsErr = conn.lastError();
    // 		auto text = lsErr.text();
    // 		QMessageBox::critical(nullptr, "出错信息", text, QMessageBox::Ok);
    // 		model->revertAll();
    // 		return;
    // 	}

}

void MainWindow::onBtnDeleteLine()
{
#ifdef _DEBUG
    qDebug() << "onBtnDeleteLine";
#endif //_DEBUG

    // 获取当前的行
    auto index = ui->tableView->currentIndex().row();
    // 移除当前的行
    if (index == -1) {
        auto re = QMessageBox::warning(nullptr, "提示信息", "当前么有选定任何一行,\n 是否取消本次操作?", QMessageBox::Ok, QMessageBox::Cancel);

        if (re == QMessageBox::Ok) {
            return;
        }
        else {
            return;
        }
    }
    model->removeRow(index);
#ifdef _DEBUG
    qDebug() << "当前选中的行是 " << ui->tableView->currentIndex().row();
#endif // _DEBUG


    auto re = QMessageBox::warning(nullptr, "提示信息", "是否确定此操作", QMessageBox::Ok, QMessageBox::Cancel);

    if (re == QMessageBox::Ok) {

        auto re = model->submitAll();
        if (!re) {
            // 如果提交不成功
            auto lsErr = conn.lastError();
            auto text = lsErr.text();
            QMessageBox::critical(nullptr, "出错信息", text, QMessageBox::Ok);
            model->revertAll();
            return;

        }
    }
    else {	//撤销操作
        model->revertAll();
    }


}

void MainWindow::onTimerUp()
{
    QTime time = QTime::currentTime();

    mStaLabel->setText(time.toString()+" --   "+tr("< a  href=https://www.zhihu.com >打开知乎</a>"));
}

/**
 * @brief MainWindow::setStatusBar
 * @param staLabel
 */
void MainWindow::setStatusBar(QLabel *& staLabel)
{
    staLabel = new QLabel(this);
    if (staLabel) {
        staLabel->setOpenExternalLinks(true);		//设置为可以打开外部链接
        ui->statusBar->addWidget(staLabel);
        staLabel->setStyleSheet("{width:100%; height:30px;font: 50 10pt 'Consolas';border-image:url(:image/label.png);}");
        staLabel->setTextFormat(Qt::RichText);
        staLabel->setFixedHeight(30);
    }
}

void MainWindow::onTableNameChange(QString tableName)
{
    qDebug()<<"onTableNameChange" <<" "<<tableName;
    setWindowTitle(conn.databaseName() + "__" + tableName);

    if(model){
        delete model;
       model =nullptr;
    }
    model = new QSqlTableModel(this);
    model->setTable(tableName);
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    ui->tableView->setModel(model);




    mStrTableName = tableName;			//重新给mStrTableName 赋值
}

void MainWindow::setAttribute()
{


#ifdef _DEBUG
    qDebug() << ui->lineEdit_host->text();
    qDebug() << "链接按钮的提示文字是 :" << ui->btn_connect->text();
    qDebug() << "当前显示数据库类型的tip" << ui->cmbsql->currentText();


#endif // _DEBUG

    ui->cmbsql->setStyleSheet("height:25px; width:150px;");
    ui->cmbsql->setCurrentIndex(ui->cmbsql->currentIndex());		//这只索引的下表
    ui->lineEdit_host->setText("localhost");
    if (ui->cmbsql->currentText().toUpper() == "MYSQL") {
        ui->lineEdit_port->setText("3306");
    }


    ui->lineEdit_userPassword->setEchoMode(QLineEdit::Password);
}

void MainWindow::setConnect()
{
    //链接的数据库类型
    connect(ui->cmbsql, SIGNAL(currentIndexChanged(QString)), this, SLOT(onSqlTypeChange()));
    // 链接数据库的动作
    connect(ui->btn_connect, SIGNAL(clicked(bool)), this, SLOT(onBtnConnect()));
    // 关闭链接
    connect(ui->btn_disConnect, SIGNAL(clicked(bool)), this, SLOT(onBtnDisConnect()));
    // 提交用户修改
    connect(ui->btn_modify, SIGNAL(clicked(bool)), this, SLOT(onBtnModify()));
    // 撤销修改
    connect(ui->btn_undomodify, SIGNAL(clicked(bool)), this, SLOT(onBtnUnModify()));
    // 新添加一行
    connect(ui->btn_input, SIGNAL(clicked(bool)), this, SLOT(onBtnInput()));
    // 删除一行
    connect(ui->btn_delete, SIGNAL(clicked(bool)), this, SLOT(onBtnDeleteLine()));
   //show 表格
    connect(ui->btn_show, SIGNAL(clicked()), this, SLOT(onBtnShow()));
    //显示新的表格
    connect(ui->btn_execSql, SIGNAL(clicked()), this, SLOT(onBtnExecSql()));
   //数据库的表格的名字发生改变
    connect(ui->cTableName,SIGNAL(currentIndexChanged(QString)),this,SLOT(onTableNameChange(QString)));
}

void MainWindow::setCountPutStr(QString & text)
{
    iPreCount = static_cast<int>(strCmd.size());
    strCmd.push_back(text);
}

void MainWindow::initialAction(QAction *& action,QObject * parent , QString text)
{
    action = new QAction(text, parent);

}

void MainWindow::initialMenu(QMenu *& menu, QMenuBar * parent, QString title)
{
    menu = new QMenu (title, parent);
}

void MainWindow::initialMenuBar()
{
    auto menubar = new QMenuBar(this);

    qDebug() << "menubar = " << menubar;
    QMenu *menu;
    QAction *action;
    initialMenu(menu, menubar, "说明");
    if (!menu) {
        initialAction(action, menu, "说明");
        if (action) {
            menubar->addMenu(menu);
            menu->addAction(action);
        }
    }
    else {
        return;
    }
}

QCompleter *MainWindow::initialComPleter(QStringList &list,QObject * parent)
{
    return new QCompleter(list,parent);

}



void MainWindow::onBtnShow()
{

    ui->lineEditSql->clear();		//清零sql 语句的编辑框
    // 判断是否已经链接数据库实例
    if (!conn.isOpen()) {
        QMessageBox::information(nullptr, "information", "数据库还没有链接", QMessageBox::Ok);
        return;
    }

    QString strTableName = ui->cTableName->currentText().trimmed(); // 获取表名
    // 判断表名不能为空
    if (strTableName == "") {
        QMessageBox::information(nullptr, "information", "显示的表名不能为空", QMessageBox::Ok);
        return;
    }
#ifdef _DEBUG
    qDebug() << "表名是: " << strTableName;
    qDebug() << " host name is " << conn.hostName();
    qDebug() << "onBtnShow()";

#endif

    // 获取表名列表
    auto tableNameList = conn.tables();

#ifdef _DEBUG
    qDebug() << tableNameList;
#endif // _DEBUG
    // 如果 列表已经包含该表
    if (tableNameList.contains(strTableName)) {
        // 判断当前的表是否是当前显示的列表
        if (model) {
            if (model->tableName() == strTableName) {
                setWindowTitle(conn.databaseName() + "__" + strTableName);

                return;
            }
            else {  // 如果该表已经存在 , 但是不是在显示 更新model
                delete model;
                model = nullptr;

                model = new QSqlTableModel(this);
#ifdef _DEBUG

                qDebug() << "table name" << strTableName << " , title's name " << conn.databaseName() + "__" + strTableName;

#endif // _DEBUG
                // 设置标题
                setWindowTitle(conn.databaseName() + "__" + strTableName);

                model->setTable(strTableName);
                model->setEditStrategy(QSqlTableModel::OnManualSubmit);
                model->select();
                ui->tableView->setModel(model);

                mStrTableName = strTableName;


                mStrTableName = strTableName;			//重新给mStrTableName 赋值
                return;
            }
        }
        else {
            model = new QSqlTableModel(this);
#ifdef _DEBUG

            qDebug() << "table name" << strTableName << " , title's name " << conn.databaseName() + "__" + strTableName;

#endif // _DEBUG
            // 设置标题
            setWindowTitle(conn.databaseName() + "__" + strTableName);

            model->setTable(strTableName);
            model->setEditStrategy(QSqlTableModel::OnManualSubmit);
            model->select();
            ui->tableView->setModel(model);

            mStrTableName = strTableName;


            mStrTableName = strTableName;			//重新给mStrTableName 赋值
            return;

        }

    }


    auto re = QMessageBox::warning(nullptr, "警告", "该数据库没有存在该表,是否创建", QMessageBox::Ok, QMessageBox::Cancel);

    if (re == QMessageBox::Ok) {
        ui->lineEditSql->setText("create table " + strTableName);
        return;
    }
    else {
        ui->lineEditSql->clear();	//清除lineSql语句选项的wen文本
        return;
    }




}
